import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  FlatList,
  ActivityIndicator,
} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import AreaView from '../../components/Layout/AreaView';
import {enrollList} from '../../service/my';
import styles from './style';

const ps = 10;
const Apply = () => {
  const navigation = useNavigation();
  const [pn, setPn] = useState(1);
  const [list, setList] = useState([]);
  const [refreshing, setRefreshing] = React.useState(false);
  const [total, setTotal] = React.useState(0);
  const renderItem = ({item}) => {
    return (
      <TouchableOpacity
        activeOpacity={1}
        style={styles.list}
        onPress={() => {
          navigation.push('ApplyDetail', {
            erId: item.erId,
          });
        }}>
        <Text style={styles.title}>{item.erTitle}</Text>
        <Text style={styles.desc} numberOfLines={3}>
          {item?.content?.replace(/<\/?.+?\/?>/g, '')}
        </Text>
        <Text style={styles.desc}>
          活动时间：{item.beginTime} ～ {item.endTime}
        </Text>
      </TouchableOpacity>
    );
  };

  useEffect(() => {
    enrollList({pn}).then((res) => {
      console.log(res);
      setList(res.rows);
      setTotal(res.total || 0);
      let _list = list;
      if (pn * 1 !== 1) {
        _list = _list.concat(res.rows);
      } else {
        _list = res.rows;
        setRefreshing(false);
      }
      setList(_list || []);
    });
  }, [pn]);

  const onEndReached = () => {
    if (pn * 10 > total) {
      return false;
    }
    const num = pn + 1;
    setPn(num);
  };
  return (
    <AreaView>
      <FlatList
        style={styles.container}
        refreshing={refreshing}
        showsVerticalScrollIndicator={false}
        data={list}
        renderItem={renderItem}
        keyExtractor={(item) => item.erId}
        onEndReachedThreshold={0.2}
        onEndReached={onEndReached}
        ListFooterComponent={() => (
          <View style={styles.footer_loading}>
            {ps * pn > (total || 10) ? (
              <Text style={styles.footer_text}>到底了。。。</Text>
            ) : (
              <ActivityIndicator
                animating={true}
                color="#666"
                text="数据加载中......"
              />
            )}
          </View>
        )}
      />
    </AreaView>
  );
};

export default Apply;
